import { Component, OnInit, ElementRef, DoCheck, OnDestroy } from '@angular/core';
import { Subject } from 'rxjs';
import { useResizeObserver } from '../../../util';

@Component({
  selector: 'bz-view-header',
  templateUrl: './view-header.component.html'
})
export class ViewHeaderComponent implements OnInit, DoCheck, OnDestroy {

  public heightChange$ = new Subject();
  private height: number;
  private isWatchHeight = false;
  private resizeObserver;

  constructor(
    private ele: ElementRef
  ) { }

  public watchHeight() {
    this.isWatchHeight = true;
    if (useResizeObserver) {
      this.resizeObserver = new (<any>window).ResizeObserver(this.compareHeight.bind(this));
      this.resizeObserver.observe(this.ele.nativeElement, { box: 'border-box' });
    } else {
      this.compareHeight();
    }
  }

  ngOnInit() {
  }

  ngDoCheck(): void {
    if (!this.isWatchHeight || useResizeObserver) {
      return;
    }

    this.compareHeight();
  }

  compareHeight() {
    const height = this.ele.nativeElement.clientHeight;
    if (this.height !== height) {
      this.heightChange$.next(height);
      this.height = height;
    }
  }

  ngOnDestroy(): void {
    if (this.resizeObserver) {
      this.resizeObserver.disconnect();
    }
  }
}
